package com.uuj.project.base;

import com.uuj.project.base.BaseResponse;
import com.uuj.project.listener.NetResultCallBack;
import com.uuj.project.net.CommonSubscriber;
import com.uuj.project.net.IApiService;
import com.uuj.project.net.IPresenter;
import com.uuj.project.net.NetController;
import com.uuj.project.net.NetRequest;
import com.uuj.project.net.RxUtil;
import com.uuj.project.view.IBaseView;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

import io.reactivex.Flowable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.subscribers.ResourceSubscriber;

/**
 * ProjectName:    ok_rxjava_retrofit
 * Package:        com.uuj.project.presenter
 * ClassName:      BasePresenter
 * Description:    描述
 * Author:         张继
 * CreateDate:     2019/8/8 11:34
 * UpdateUser:     更新者
 * UpdateDate:     2019/8/8 11:34
 * UpdateRemark:   更新说明
 * Version:        1.0
 */
public class BasePresenter<V extends IBaseView> implements IPresenter {

    private Reference<V> reference;

    public BasePresenter(V view) {
        reference = new WeakReference<V>(view);
    }

    /**
     * 请求网络
     *
     * @param tClass     class
     * @param flowable   接口
     * @param subscriber 接受数据
     */
    protected <T> void subscription(Class tClass, Flowable<BaseResponse<Object>> flowable, ResourceSubscriber subscriber) {
        NetController.<T>getInstance().netServer(tClass, flowable, subscriber);
    }




    @Override
    public void onStart() {

    }

    @Override
    public void onResume() {

    }

    @Override
    public void onPause() {

    }

    @Override
    public void onStop() {

    }

    @Override
    public void onRestart() {

    }

    /**
     * 解除绑定
     */
    @Override
    public void detachView() {
        if (isViewAttach()) {
            reference.clear();
            reference = null;
        }
    }

    public V getView() {
        if (isViewAttach()) {
            return reference.get();
        }
        return null;
    }

    protected IApiService getService() {
        return NetRequest.getInstance().getService();
    }

    /**
     * 主要用于判断IView的生命周期是否结束，防止出现内存泄露状况
     *
     * @return true表示有值 false表示为空
     */
    protected boolean isViewAttach() {
        return reference != null && reference.get() != null;
    }

    /**
     * 根据资源id获取string字符串
     *
     * @param id 字符串id
     * @return 返回字符串
     */
    public String getString(int id) {
        return getView().getBaseActivity().getString(id);
    }

}
